package org.cnbi.web.controller;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cnbi.entity.IndicatorExpression;
import org.cnbi.entity.Menu;
import org.cnbi.service.IComposeService;
import org.cnbi.service.IDashService;
import org.cnbi.service.IndustryParamsService;
import org.cnbi.utils.convert.OjbectConvertUtil;
import org.cnbi.utils.date.DateUtil;
import org.cnbi.utils.json.JsonUtil;
import org.cnbi.utils.pingyin.PingYinUtil;
import org.cnbi.utils.pojo.MsgBean;
import org.cnbi.utils.pojo.SqlParamsBean;
import org.cnbi.utils.pojo.UtilDim;
import org.cnbi.utils.pojo.dash.ItemBean;
import org.cnbi.utils.pojo.dash.ModelBean;
import org.cnbi.utils.pojo.indicator.IndicatorDimBean;
import org.cnbi.utils.pojo.indicator.IndicatorParams;
import org.cnbi.utils.pojo.indicator.ItemUtil;
import org.cnbi.utils.pojo.industry.IndustryParamBean;
import org.cnbi.utils.string.StringUtil;
import org.cnbi.utils.tools.ActionConstants;
import org.cnbi.utils.tools.Constants;
import org.cnbi.utils.tools.GlobalConstants;
import org.cnbi.utils.tools.MenuConstants;
import org.cnbi.utils.tools.SymbolConstants;
import org.cnbi.utils.xml.XMLUtils;
import org.cnbi.utils.xml.YcDashXmlParser;
import org.cnbi.web.controller.base.BaseController;
import org.dom4j.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;



/**
 * 系统请求页面的核心控制器 凡是是请求页面的动作，都到这里来写吧！ 
 * Copyright © 2014中国经邦. All rights reserved.
 * @author 龚佳新
 * @date 2014年4月17日下午12:47:04
 * @cnbi-web
 */
@Controller
@RequestMapping("/dash")
public class DashController extends BaseController {
	
	private static final Log logger = LogFactory.getLog(DashController.class);
	@Autowired
	private IDashService dashService;
	
	@Autowired
	private IComposeService composeService;
	
	@Autowired
	private IndustryParamsService industryParamsService;
	
	
	
	@RequestMapping(value = "/index")
	public ModelAndView main(HttpServletResponse response) {
		return firstNavHandle(MenuConstants.DASH,response);
	}
	
	/**
	 * 响应二级菜单页面
	 * 
	 * @param param
	 * @param menu
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/" + MenuConstants.LEVELTWO)
	public ModelAndView levelTwo(SqlParamsBean param, Menu menu, HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = secondNavHandle(menu, response);
		String type = param.getDimarr()[0];
		menu.setSpcode(type);
		String filePath = getRealPath("xml"+File.separator+type);//xmlFilePath+path+File.separatorChar+xml;
		String scode = menu.getScode();
		try {
		    Object object = null;
			if(menu.getScode().equals("debt")){//
				List<ModelBean> list= new ArrayList<ModelBean>();
				for(int i=1;i<6;i++){
					  Document doc = XMLUtils. parseFileToXml(filePath+scode+i+".xml");  
					  ModelBean bean= getDashObject(doc);
					  list.add(bean);
					  getServletContext().setAttribute(bean.getId(), bean);
				}
				object = list;
			}else{
				  filePath = filePath+scode+".xml";
				  Document doc = XMLUtils. parseFileToXml(filePath);  
				  object = getDashObject(doc);
				  getServletContext().setAttribute(scode, object);
			}
			
			view.addObject(Constants.DATAS, object);
			String jsonDatas = JsonUtil.generateJson(object);
			view.addObject("jsonDatas", jsonDatas);
			dimMapHandle(view, param, menu);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return view;
	}

	/**
	 * @param doc
	 * @return
	 * @throws Exception
	 */
	private ModelBean getDashObject(Document doc) throws Exception {
		YcDashXmlParser sys = new YcDashXmlParser(doc);
		ModelBean  object = (ModelBean)sys.execute();
		return object;
	}
	@RequestMapping(value = "/industry")
	@ResponseBody
	private Object queryIndustryParams(IndustryParamBean param){
		return getIndustryParams(param);
	}
	/**
	 * 指标钻取响应
	 * @param type ==1代表是加减的
	 *        type ==2代表是乘除的
	 * @param 
	 *        param.season  代表传过来的直接是指标Id
	 *        
	 * @return
	 */
	@RequestMapping(value = "/drill")
	@ResponseBody
	private Object drill(IndicatorParams queryParam,@RequestParam(value = "year") int year,@RequestParam(value = "month") String month){
		String name = "";
		int yearArr[] = {year,year-1};
		long a = System.currentTimeMillis();
		Map<Integer,List<IndicatorDimBean>> map = new LinkedHashMap<Integer,List<IndicatorDimBean>>();
		for (int ys : yearArr) {
			queryParam.setPeriod(DateUtil.getYearData(ys).split("\\"+SymbolConstants.COMMON));
			List<IndicatorDimBean> list = OjbectConvertUtil.getIndicatorDimBeanList(getIndicatorMap(),queryParam);
			Map<String, String> sqlMap = getSqlMap();
			for (int i=0,len = list.size();i<len;i++){
				IndicatorDimBean bean = list.get(i);
				bean.setCompanyName(getCompany(bean.getCompany()).getSname());
				bean.setPeriodName(StringUtil.getPeriodName(bean.getPeriod()));
				IndicatorExpression datas = composeService.queryIndicatorList(sqlMap,bean);
				bean.setIndicatorBean(datas);
				name = datas.getName();
			//	logger.info(datas.getName()+bean.getCompanyName()+bean.getPeriodName()+"==="+datas.getDatas());
			}
			map.put(ys, list);
		}
		long b = System.currentTimeMillis();
		logger.info(name+"查24个月的数据共历时"+(b-a)+"毫秒！");
		return map;
	}
	
	
	/**
	 * 查询行业参数
	 * @param param
	 * @return
	 */
	private Object getIndustryParams(IndustryParamBean param){
		  String sql = getSqlByKey(ActionConstants.INIT+"industry");
		  List<IndustryParamBean> queryList = param.getQueryIndustryParamBeanList(getCompany(param.getCompany()));
		  Map<String,IndustryParamBean> map = new LinkedHashMap<String,IndustryParamBean>();
		  for (IndustryParamBean industryParamBean : queryList){
			  if(null == industryParamBean.getId()){
				  UtilDim dim = getDimByKeyAndScode(Constants.DIM_INDUSTRYPARAMS, industryParamBean.getCode());
				  if(null == dim){
					  logger.error("查询行业参数"+industryParamBean+"出错了！");
				  }
				  String id = PingYinUtil.getFirstSpell(dim.getSname());
				  industryParamBean.setId(id);
			  }
			  IndustryParamBean bean = industryParamsService.queryIndustryParamBean(sql,industryParamBean);
			  map.put(industryParamBean.getId(),bean);
		  }
		return map;
	}
	/**
	 * 查询模型数据公共方法
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "/datas")
	@ResponseBody
	private Object datas(SqlParamsBean param){
		String dashId = param.getSeason(),factsplit = Constants.FACT+SymbolConstants.UNDERLINE;
		ModelBean db = (ModelBean) getServletContext().getAttribute(dashId);
		List<Object> list = db.getQueryItems();
		String factType = db.getFactType();
		Map<String, BigDecimal> resultMap = new HashMap<String, BigDecimal>();
		/**
		 * 度量不统一的查询 
		 */
		if(StringUtil.isBlank(factType)){
			for (Object object : list){
				ItemBean bean = OjbectConvertUtil.getItemBean(object,db);
				String sql = getSqlMap().get(bean.getSubject());
				String period = DateUtil.getRelativePeriod(bean.getPeriod(), param.getPeriod());
				BigDecimal datas = dashService.queryBigDicamal(sql,new ItemUtil(bean.getScode(),factsplit+bean.getFact(),param.getCompany(),period));
				resultMap.put(bean.getId(), datas);
			
			}
	   }else{
		  /**
		   * 度量统一的查询 
		   */
		   String sql = getSqlMap().get(db.getSubject());
		   ItemUtil itemBean = new ItemUtil(dashId,factType,param.getCompany(), param.getPeriod());
		   resultMap = dashService.queryMapBean(sql,itemBean, db);
	   }
		return resultMap;
	}
	
	
}
